package com.conversationboard.email;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

class SmtpMail implements IMail {

	private String host;
	private Session session;


	public String getHost() {
		return host;
	}


	public void setHost(String host) {
		this.host = host;
	}


	public SmtpMail(String host) {

		this.setHost(host);

		Properties properties = System.getProperties();
		properties.put("mail.smtp.host", this.getHost());

		Session session = Session.getDefaultInstance(properties, null);
		this.session = session;
	}


	public void send(String from, String recipients, String subject, String body) throws MessagingException {

		Message message = new MimeMessage(this.session);
		message.setSubject(subject);
		message.setFrom(new InternetAddress(from));
		InternetAddress[] addresses = InternetAddress.parse(recipients, false);
		message.setRecipients(Message.RecipientType.TO, addresses);

		if (!body.trim().startsWith("<html")) {
			message.setText(body);
		} else {
			Multipart multiPart = new MimeMultipart();

			BodyPart bodyPart = new MimeBodyPart();
			bodyPart.setText(body);
			bodyPart.setHeader("content-type", "text/html");

			multiPart.addBodyPart(bodyPart);

			message.setContent(multiPart);
		}

		Transport.send(message);

	}

}
